import { Upload, message } from 'antd';
import React, { FC, useState } from 'react';
import { FormInstance } from 'antd/lib/form';
import styles from './index.less';
import IconFont from '@/components/IconFont';
import { useUpdateEffect } from 'ahooks';

function getBase64(img: any, callback: (reader: any) => void) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

interface AddUploadProps {
  formRef: React.MutableRefObject<FormInstance | undefined>;
  photo: string;
}
const AddUpload: FC<AddUploadProps> = ({ formRef, photo }) => {
  const [state, setState] = useState({ imageUrl: '' });
  useUpdateEffect(() => {
    setState({
      imageUrl: formRef.current?.getFieldsValue()?.photo || '',
    });
  }, [photo]);

  const beforeUpload = (file: any) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('只支持上传JPG/PNG文件!');
      return false;
    }
    getBase64(file, (imageUrl) => {
      formRef.current?.setFieldsValue({
        photo: imageUrl,
      });

      setState({
        imageUrl,
      });
    });
    return false;
  };
  const uploadButton = (
    <div>
      <IconFont type={'iconxiaoxiang'} className={styles['no-data']} />
    </div>
  );
  const { imageUrl } = state;
  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className={styles['add-upload-form']}
      showUploadList={false}
      beforeUpload={beforeUpload}
    >
      {imageUrl ? <img src={imageUrl} alt="照片" style={{ width: '100%' }} /> : uploadButton}
    </Upload>
  );
};

export default AddUpload;
